#include "mutex.hpp"
#include <unistd.h>

int ticket = 1000;

void *start_routine(void *args)
{
    Mutex::data *_pdata = static_cast<Mutex::data *>(args);
    while (1)
    {
        {
            pthread_mutex_lock(_pdata->_pmutex);
            if (ticket > 0)
            {
                ticket--;
                std::cout << _pdata->_name << " " << "ticket: " << ticket << std::endl;
                pthread_mutex_unlock(_pdata->_pmutex);
            }

            else
            {
                pthread_mutex_unlock(_pdata->_pmutex);
                break;
            }
        }
    }

    return nullptr;
}

int main()
{

    std::vector<pthread_t> _vpthread = {0, 1, 2, 3};
    Mutex::mutex _mutex;
    std::vector<Mutex::data> _vdata(4);
    for (int i = 0; i < 4; i++)
    {
        std::string _name = "thread_";
        _name += std::to_string(i + 1);
        _vdata[i] = {_name, &_mutex};
        pthread_create(&_vpthread[i], nullptr, start_routine, (void *)&_vdata[i]);
    }

    for (auto &tid : _vpthread)
    {
        pthread_join(tid, nullptr);
        std::cout << "回收新线程成功: " << tid << std::endl;
    }

    return 0;
}
